import java.io.File;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetAddress;




public class Sender {

	public static void main(String[] args) throws IOException, InterruptedException {
		
		final int H = 16;
		//final String hostR ="192.168.1.106";
		//final String hostS ="192.168.1.106";
		//final String hostC ="192.168.1.100";
		final String hostR = "127.0.0.1";
		final String hostS = "127.0.0.1";
		final String hostC = "127.0.0.1";
		final InetAddress IPChannel = InetAddress.getByName(hostC);
		final int portChannel = 65432;
		final InetAddress IPDestination = InetAddress.getByName(hostR);
		final int portDestination = 65433;
		final InetAddress IPSource = InetAddress.getByName(hostS);
		final int portSource = 65431;
		final int portACK = 65435;
		
		
		DatagramSocket sendingSocket = new DatagramSocket(portSource);
		DatagramSocket ACKsocket = new DatagramSocket(portACK);
		double x = ping(hostC)/2;  //ping
		
		
		//INPUT FILE
		String path = "/home/gguerra/prova";
		//String path = "/home/gguerra/Scrivania/balmain-dev munin installation.odt";
		//String path ="/home/gguerra/Scaricati/2015-01-08 18.53.03.jpg";
		//String path = "/home/gguerra/Scaricati/2014.11.20 ens 1.MP3";
		//System.out.println("Path... "+path);
		
		File file= new File(path.trim());
		Handshaker HS = new Handshaker(IPDestination, portDestination, IPChannel, portChannel, IPSource, portSource, portACK, x, H, file.length(), sendingSocket, ACKsocket);
		HS.start();
		
		
		double y = HS.gety(); //ping
		int L = HS.getL();
		int N = HS.getN();
		
		System.out.println("Ping y:"+2*y+" N: "+N+" L: "+L );
		
		Cell[] tabella = new Cell[N];
		Splitter sp = new Splitter(file, L, tabella, IPDestination, portDestination, IPSource, portACK);
		Thread t = new Thread(sp);
		t.start();
		Thread.sleep(100);
		SendService sendService = new SendService(IPChannel, tabella, sendingSocket, N, L);
		Thread s = new Thread(sendService);
		s.start();
		DaemonReceiver daemon = new DaemonReceiver(ACKsocket, tabella);
		daemon.runDR();
		
		
		while (!sendService.isSafe()){}
	
		System.out.println("File Inviato.");	
	}
	
	public static double ping (String hostC) throws IOException {
		
		PingArguments arguments = new PingArguments.Builder().url(hostC)
				.timeout(5000).count(5).bytes(32).build();
		
		PingResult results = Ping.ping(arguments, Ping.Backend.UNIX);
		return results.rtt_avg();
	
	}
	
}







